package javaweb;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP {
    private Socket socket;
    private ServerSocket serverSocket;
    @Test
    public void Server(){
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){
            //1.创建服务器端的ServerSocket对象,指明自己的端口号
            serverSocket = new ServerSocket(8088);
            //2.调用accecp()接收来自客户端的socket
            Socket accept = serverSocket.accept();
            //3.获取输入流,写出数据
            InputStream inputStream = accept.getInputStream();
            //可能会产生乱码
//            int len;
//            byte[] bytes=new byte[1024];
//            while ((len=inputStream.read(bytes))!=-1){
//                System.out.println(new String(bytes,0,len));
//            }
            byte[] bytes=new byte[10];
            int len;
            while ((len=inputStream.read(bytes))!=-1){
                baos.write(bytes,0,len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void Client() {
        try {
            //1.创建客户端的Socket对象,指明服务器的端口号和ip
            InetAddress address = InetAddress.getByName("localhost");
            socket = new Socket(address,8088);
            //2.获取一个输出流,写出数据
            OutputStream sos = socket.getOutputStream();
            sos.write("喵喵喵".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
